<template>
  <div class="register_page">
    <Logo />
    <div class="content">
      <div class="content_left">
        <div class="title">欢迎使用互盛科技产融数字服务平台</div>
        <div class="describtion">
          为核心企业、供应链上下游企业及金融机构建立良好的沟通渠道，促使多方互信、合作、共赢
        </div>
        <img src="@/assets/register/welcome.png" alt="" class="welcome_img" />
      </div>
      <div class="content_right">
        <div class="form_box">
          <h3 class="title">欢迎登录互盛科技</h3>
          <el-tabs v-model="currentLoginType" class="tabs">
            <el-tab-pane label="密码登录" name="passwordLogin">
              <el-form
                ref="passwordLogin"
                :model="passwordLoginForm"
                :rules="passwordLoginRules"
              >
                <el-form-item prop="username">
                  <el-input
                    v-model="passwordLoginForm.username"
                    type="text"
                    auto-complete="off"
                    placeholder="请输入管理员手机号"
                    :clearable="true"
                  >
                    <i slot="prefix" class="el-icon-mobile-phone"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input
                    v-model="passwordLoginForm.password"
                    type="password"
                    auto-complete="off"
                    placeholder="请输入登录密码"
                    @keyup.enter.native="handleRegister"
                    :clearable="true"
                  >
                    <i slot="prefix" class="el-icon-lock" />
                  </el-input>
                </el-form-item>
                <el-form-item prop="code">
                  <div class="get_code_line">
                    <el-input
                      v-model="passwordLoginForm.code"
                      auto-complete="off"
                      placeholder="验证码"
                      class="code_input"
                      :clearable="true"
                      @keyup.enter.native="handlePasswordLogin"
                    >
                      <svg-icon
                        slot="prefix"
                        icon-class="validCode"
                        class="el-input__icon input-icon"
                      />
                    </el-input>
                    <div class="login_code">
                      <img :src="codeUrl" @click="getCodeImg" class="login-code-img" />
                    </div>
                  </div>
                </el-form-item>
                <el-form-item prop="agreement" class="agree_line">
                  <el-checkbox
                    v-model="passwordLoginForm.agreement"
                  ></el-checkbox>
                  <span class="agree_txt">我已阅读并同意</span>
                  <a
                    class="agreement agreement_1"
                    :href="baseURL + downloadTemplate3.fileUrl"
                    target="_blank"
                  >《互盛科技平台服务协议》、</a>
                  <a
                    class="agreement agreement_2"
                    :href="baseURL + downloadTemplate5.fileUrl"
                    target="_blank"
                    >《平台用户隐私政策》</a>
                </el-form-item>
                <el-form-item style="width: 100%; margin-bottom: 0">
                  <el-button
                    :loading="loading"
                    size="medium"
                    type="primary"
                    class="login_btn"
                    @click.native.prevent="handlePasswordLogin"
                  >
                    <span v-if="!loading">登 录</span>
                    <span v-else>登 录 中...</span>
                  </el-button>
                </el-form-item>
                <div class="forget_password_box">
                  <el-button type="text" class="forget_password" @click="gotoForgetPassword">忘记密码</el-button>
                  <div>
                    还没有账号？
                    <el-button type="text" style="padding: 0" @click="gotoRegister"
                      >立即注册</el-button
                    >
                  </div>
                </div>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="验证码登录" name="codeLogin">
              <el-form
                ref="codeLogin"
                :model="codeLoginForm"
                :rules="codeLoginRules"
              >
                <el-form-item prop="phonenumber">
                  <el-input
                    v-model="codeLoginForm.phonenumber"
                    type="text"
                    auto-complete="off"
                    placeholder="请输入管理员手机号"
                    :clearable="true"
                  >
                    <i slot="prefix" class="el-icon-mobile-phone"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="code" class="code_line">
                  <el-input
                    v-model="codeLoginForm.code"
                    auto-complete="off"
                    placeholder="请输入短信验证码"
                    @keyup.enter.native="handleCodeLogin"
                  >
                    <i slot="prefix" class="el-icon-mobile-phone"></i>
                  </el-input>
                  <el-button type="text" class="get_code" :loading="codeLoading" @click="getCode"
                    >{{ sNumber > -1 ? sNumber + 's' : '获取验证码' }}</el-button
                  >
                </el-form-item>
                <el-form-item prop="agreement" class="agree_line">
                  <el-checkbox v-model="codeLoginForm.agreement"></el-checkbox>
                  <span class="agree_txt">我已阅读并同意</span>
                  <a
                    class="agreement agreement_1"
                    :href="baseURL + downloadTemplate3.fileUrl"
                    target="_blank"
                  >《互盛科技平台服务协议》、</a>
                  <a
                    class="agreement agreement_2"
                    :href="baseURL + downloadTemplate5.fileUrl"
                    target="_blank"
                  >《平台用户隐私政策》</a>
                </el-form-item>
                <el-form-item style="width: 100%; margin-bottom: 0">
                  <el-button
                    :loading="loading"
                    size="medium"
                    type="primary"
                    class="login_btn"
                    @click.native.prevent="handleCodeLogin"
                  >
                    <span v-if="!loading">登 录</span>
                    <span v-else>登 录 中...</span>
                  </el-button>
                </el-form-item>
                <div class="forget_password_box">
                  <el-button type="text" class="forget_password" @click="gotoForgetPassword">忘记密码</el-button>
                  <div>
                    还没有账号？
                    <el-button type="text" style="padding: 0" @click="gotoRegister"
                      >立即注册</el-button
                    >
                  </div>
                </div>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <Copyright />
  </div>
</template>

<script>
import { getCode, getCodeImg } from "@/api/login";
import Logo from "@/customComponents/logo";
import Copyright from "@/customComponents/copyright";
import colors from "@/assets/styles/variables.scss";
import { downloadTemplate } from "@/api/authenticate";
import { Message } from 'element-ui'

export default {
  name: "Login",
  components: {
    Logo,
    Copyright,
  },
  data() {
    return {
      baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API :
        process.env.VUE_APP_HTTP_REQUEST_ADDRESS,
      themeColor: colors.themeColor,
      currentLoginType: "passwordLogin",
      codeUrl: '',
      passwordLoginForm: {
        username: "",
        password: "",
        code: "",
        agreement: false,
      },
      codeLoginForm: {
        phonenumber: "",
        code: "",
        uuid: "",
        agreement: false,
      },
      passwordLoginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入管理员手机号" },
          {
            validator: (rule, value, callback) => {
              console.log(value)
              if (/^1\d{10}/.test(value)) {
                callback()
              } else {
                callback('请输入正确手机号')
              }
            },
            trigger: ["change", 'blur'],
          },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
          {
            pattern: /^[^<>"'|\\]+$/,
            message: "不能包含非法字符：< > \" ' \\\ |",
            trigger: "blur",
          },
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
        agreement: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                callback();
              } else {
                callback("请勾选协议");
              }
            },
            trigger: "change",
          },
        ],
      },
      codeLoginRules: {
        phonenumber: [
          { required: true, trigger: "blur", message: "请输入管理员手机号" },
          {
            validator: (rule, value, callback) => {
              if (/^1\d{10}/.test(value)) {
                callback();
              } else {
                callback("请输入正确手机号");
              }
            },
            trigger: "blur",
          },
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
        agreement: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                callback();
              } else {
                callback("请勾选协议");
              }
            },
            trigger: "change",
          },
        ],
      },
      loading: false,
      downloadTemplate3: {
        fileUrl: '',
        fileType: '',
        agreementName: '',
      },
      downloadTemplate5: {
        fileUrl: '',
        fileType: '',
        agreementName: '',
      },
      codeLoading: false,
      sNumber: -1, // 倒计时
      timer: null, // 倒计时
    };
  },
  mounted() {
    this.downloadTemplate(3).then((res) => {
      this.downloadTemplate3 = res.data;
    }); // 互盛科技平台服务注册协议
    this.downloadTemplate(5).then((res) => {
      this.downloadTemplate5 = res.data;
    }); // 平台用户隐私协议
    this.getCodeImg()
  },
  methods: {
    // 下载模板
    downloadTemplate(id) {
      return new Promise((resolve, reject) => {
        downloadTemplate(id).then((res) => {
          resolve(res);
        });
      });
    },
    getCodeImg() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.passwordLoginForm.uuid = res.uuid;
        }
      });
    },
    handlePasswordLogin() {
      console.log(this.$refs);
      this.$refs.passwordLogin.validate((valid) => {
        if (valid) {
          this.loading = true;
          const { username, password, code, uuid } = this.passwordLoginForm
          this.$store
            .dispatch("Login", { username, password, code, uuid })
            .then(() => {
              console.log(this.$route.query.redirect)
              if (this.$route.query.redirect) {
                this.$router.push({
                  path: this.$route.query.redirect
                })
              } else {
                this.$router
                .push({ path: '/' })
              }
            })
            .catch(() => {
              this.loading = false;
              this.getCodeImg();
            });
        }
      });
    },
    countFn() {
      this.timer = setTimeout(() => {
        if (this.sNumber > -1) {
          --this.sNumber
          this.countFn()
        } else {
          clearTimeout(this.timer)
          this.timer = null
        }
      }, 1000);
    },
    countDown() {
      this.sNumber = 60
      this.countFn()
    },
    getCode() {
      this.$refs.codeLogin.validateField(["phonenumber"], (valid) => {
        if (!valid) {
          this.codeLoading = true
          getCode({ phonenumber: this.codeLoginForm.phonenumber }, 1).then(
            (res) => {
              this.codeLoading = false
              this.codeLoginForm.uuid = res.uuid;
              this.countDown()
            }
          ).catch(({ code, msg }) => {
            this.codeLoading = false
            if (code === 201) {
              Message({ message: msg, type: 'error' })
            }
          });
        }
      });
    },
    handleCodeLogin() {
      this.$refs.codeLogin.validate((valid) => {
        if (valid) {
          this.loading = true;
          const { phonenumber, code, uuid } = this.codeLoginForm
          // username: '', password: '',
          this.$store
            .dispatch("Login", { phonenumber, code, uuid })
            .then(() => {
              console.log(this.$route.query.redirect)
              if (this.$route.query.redirect) {
                this.$router.push({
                  path: this.$route.query.redirect
                })
              } else {
                this.$router
                .push({ path: '/' })
              }
            })
            .catch(() => {
              this.loading = false
            });
        }
      });
    },
    gotoForgetPassword() {
      this.$router.push({
        path: '/forgetPassword'
      })
    },
    gotoRegister() {
      this.$router.push({
        path: "/register",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/px2rem.scss';
@import "@/assets/styles/variables.scss";

.register_page {
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  overflow-y: auto;
  .content {
    display: flex;
    justify-content: center;
    .content_left {
      margin-right: px2rem(118);
      .title {
        color: $theme;
        font-size: px2rem(40);
        font-weight: 600;
        height: px2rem(56);
        line-height: px2rem(56);
        margin-bottom: px2rem(12);
        text-align: center;
      }
      .describtion {
        color: #516ea3;
        font-size: px2rem(18);
        height: px2rem(52);
        line-height: px2rem(26);
        text-align: center;
        // width: px2rem(584);
        margin: 0 auto px2rem(34);
      }
      .welcome_img {
        display: block;
        width: px2rem(584);
        height: px2rem(545);
        margin: 0 auto;
      }
    }
    .content_right {
      display: flex;
      align-items: flex-start;
      .form_box {
        border-radius: px2rem(20);
        background: #ffffff;
        width: 520px;
        padding: px2rem(48);
        box-shadow: rgba(0, 88, 255, 0.4) px2rem(5) px2rem(6) px2rem(14) 0;
        .tabs {
          font-size: 16px;
        }
        .title {
          margin-bottom: px2rem(56);
          color: $theme;
          font-size: px2rem(32);
          font-weight: 600;
        }
        ::v-deep .el-tabs__nav-wrap::after {
          content: "";
          position: absolute;
          left: 0;
          bottom: 0;
          width: 100%;
          height: 2px;
          background-color: #fff;
          z-index: 1;
        }
        ::v-deep .el-tabs__item {
          font-size: 16px;
        }
        .input-icon {
          height: px2rem(39);
          width: px2rem(14);
          margin-left: px2rem(2);
        }
        .register-tip {
          font-size: 13px;
          text-align: center;
          color: #bfbfbf;
        }
        .get_code_line {
          display: flex;
          justify-content: space-between;
          .code_input {
            flex: 1 1 auto;
            margin-right: px2rem(20);
          }
          .login_code {
            width: 33%;
            height: 35px;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            .login-code-img {
              display: block;
              height: 35px;
              cursor: pointer;
            }
          }
        }
        .code_line {
          position: relative;
          .get_code {
            position: absolute;
            top: 0;
            bottom: 0;
            right: px2rem(14);
            z-index: 2;
            font-size: 14px;
          }
        }
        .register-code {
          width: 33%;
          height: px2rem(38);
          float: right;
          img {
            cursor: pointer;
            vertical-align: middle;
          }
        }
        .agree_line {
          font-size: 14px;
          ::v-deep .el-form-item__content {
            line-height: px2rem(20);
          }
          .agree_txt {
            color: #999;
            margin-left: px2rem(6);
          }
          .agreement {
            color: $theme;
            cursor: pointer;
          }
        }
      }
      .info_text {
        color: #999;
        font-size: 14px;
        line-height: px2rem(20);
        margin-top: px2rem(12);
      }
      .forget_password_box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: px2rem(20);
        color: #999;
        font-size: 14px;
        .forget_password{
          padding: 0;
          font-size: 14px;
        }
      }
      .login_btn {
        width: 100%;
        background: linear-gradient( 90deg, #0058FF 0%, #69ADFF 100%);
        border: none;
        height: px2rem(48);
        font-weight: 600;
        font-size: 18px;
        padding-top: 0;
        padding-bottom: 0;
      }
    }
  }
}
</style>
